<?php

namespace app\admin\controller\user;

use app\admin\model\UserCertification;
use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Random;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $userAuth = '';
    protected $searchFields = 'id,mobile,nickname';
    /**
     * User模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->userAuth = new Auth();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->alias('user')
                    //->with('group')
                    ->with('cert,invite1,invite2,invite3,invitetop')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->alias('user')
                    ->with('cert,invite1,invite2,invite3,invitetop')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $k => $v)
            {
                $v->hidden(['password', 'salt']);
                $v['topman'] = UserCertification::get(['user_id'=>$v['invitetop']['line_id']]);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    //  判断是否修改资金数据
                    if ($params['cny'] != $row->cny)
                    {
                        $diff = $params['cny'] - $row->cny;     //  充值或扣除的CNY
                        if ($diff > 0)
                        {
                            $total_cny = $row->total_cny + $diff;
                            array_merge($params,['total_cny' => $total_cny]);
                            $desc = '平台充值';
                        }else{
                            $desc = '平台扣除';
                        }
                        //  添加用户资金变动
                        account_log($row->id,$diff,$params['cny'] + $params['freeze_cny'],0,$params['sac'],$desc,$params['freeze_cny']);
                        //  添加平台币变动记录
                        platform_log($row->id,$diff*-1,$desc);
                    }

                    if ($params['sac'] != $row->sac)
                    {
                        $sac_diff = $params['sac'] - $row->sac;
                        if ($sac_diff > 0)
                        {
                            account_log($row->id,0,$params['cny'] + $params['freeze_cny'],$sac_diff,$params['sac'],'平台充值',$params['freeze_cny']);
                        }else{
                            account_log($row->id,0,$params['cny'] + $params['freeze_cny'],$sac_diff,$params['sac'],'平台扣除',$params['freeze_cny']);
                        }
                    }

                    //判断是否修改微信支付宝等
                    if(isset($params['wechat'])||isset($params['alipay'])||isset($params['bank_address'])||isset($params['bank_card'])||isset($params['bank_realname']))
                    {
                        $userauth = UserCertification::get(['user_id'=>$row->id]);
                        $userauth->wechat = $params['wechat'];
                        $userauth->alipay = $params['alipay'];
                        $userauth->bank_address = $params['bank_address'];
                        $userauth->bank_card = $params['bank_card'];
                        $userauth->bank_realname = $params['bank_realname'];
                        $userauth->save();
                    }
                    //  插入数据
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row = $row->toArray();
        $user = UserCertification::get(['user_id'=>$row['id']]);
        $row['wechat'] = $user->wechat;
        $row['alipay'] = $user->alipay;
        $row['bank_address'] = $user->bank_address;
        $row['bank_card'] = $user->bank_card;
        $row['bank_realname'] = $user->bank_realname;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /*
     * 添加
     */
    public function add(){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $id = Db::name('id')->find();
                    Db::name('id')->delete($id['id']);
//                    $user_num = Random::numeric(4);
                    $result = $this->userAuth->register($params['username'],$params['password'],'',$params['mobile'],['nickname'=>$params['nickname'],'id'=>$id['user_id']]);    //用户注册
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error('注册失败!手机号已存在!');
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /*
     * 验证手机号是否存在
     */
    public function mobile_unique(){
        $params = $this->request->post("row/a");
        if($params){
            $user = $this->model->get($params);
            if($user){
                return true;
            }
        }
        return false;
    }

     /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $where['id'] = ['in',$ids];
                $r = db('user')->where($where)->update(['del'=>2]);
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
